import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../base_states.dart';
import '../base_list_notifier.dart';
import '../base_detail_notifier.dart';

/// 示例数据模型
class ExampleUser {
  final int id;
  final String name;
  final String email;

  ExampleUser({
    required this.id,
    required this.name,
    required this.email,
  });

  factory ExampleUser.fromJson(Map<String, dynamic> json) {
    return ExampleUser(
      id: json['id'] ?? 0,
      name: json['name'] ?? '',
      email: json['email'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'email': email,
    };
  }
}

/// 用户列表Notifier示例
class UserListNotifier extends BaseListNotifier<ExampleUser> {
  @override
  Future<PageResponse<ExampleUser>> loadData(int page, int pageSize) async {
    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 1));

    // 模拟分页数据
    final users = List.generate(pageSize, (index) {
      final id = (page - 1) * pageSize + index + 1;
      return ExampleUser(
        id: id,
        name: 'User $id',
        email: 'user$id@example.com',
      );
    });

    return PageResponse<ExampleUser>(
      data: users,
      page: page,
      totalPage: 5, // 模拟总共5页
      totalCount: 100,
    );
  }

  @override
  void onErrorOccurred(dynamic error) {
    print('UserListNotifier error: $error');
  }

  @override
  void onRefreshSuccess() {
    print('UserListNotifier refresh success');
  }

  @override
  void onLoadMoreSuccess() {
    print('UserListNotifier load more success');
  }
}

/// 用户详情Notifier示例
class UserDetailNotifier extends BaseDetailParamNotifier<ExampleUser, int> {
  UserDetailNotifier(int userId) : super(userId);

  @override
  Future<ExampleUser> loadData(int userId) async {
    // 模拟网络请求
    await Future.delayed(const Duration(milliseconds: 800));

    return ExampleUser(
      id: userId,
      name: 'User Detail $userId',
      email: 'detail$userId@example.com',
    );
  }

  @override
  void onErrorOccurred(dynamic error) {
    print('UserDetailNotifier error: $error');
  }

  @override
  void onLoadSuccess(ExampleUser data) {
    print('UserDetailNotifier load success: ${data.name}');
  }

  @override
  void onRefreshSuccess(ExampleUser data) {
    print('UserDetailNotifier refresh success: ${data.name}');
  }
}

/// 用户编辑表单Notifier示例
class UserFormNotifier extends BaseFormNotifier<ExampleUser> {
  @override
  Future<bool> validateData(ExampleUser data) async {
    // 模拟表单验证
    if (data.name.isEmpty) return false;
    if (data.email.isEmpty) return false;
    if (!data.email.contains('@')) return false;

    return true;
  }

  @override
  Future<ExampleUser> submitData(ExampleUser data) async {
    // 模拟提交表单
    await Future.delayed(const Duration(seconds: 1));

    return data; // 返回提交后的数据
  }

  @override
  void onErrorOccurred(dynamic error) {
    print('UserFormNotifier error: $error');
  }

  @override
  void onSubmitSuccess(ExampleUser data) {
    print('UserFormNotifier submit success: ${data.name}');
  }
}

/// 简单列表Notifier示例
class SimpleUserListNotifier extends BaseSimpleListNotifier<ExampleUser> {
  @override
  Future<List<ExampleUser>> loadData() async {
    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 1));

    return List.generate(10, (index) {
      return ExampleUser(
        id: index + 1,
        name: 'Simple User ${index + 1}',
        email: 'simple${index + 1}@example.com',
      );
    });
  }

  @override
  void onErrorOccurred(dynamic error) {
    print('SimpleUserListNotifier error: $error');
  }

  @override
  void onRefreshSuccess() {
    print('SimpleUserListNotifier refresh success');
  }
}

/// 异步操作Notifier示例
class UserAsyncNotifier extends BaseAsyncNotifier<String> {
  /// 删除用户
  Future<bool> deleteUser(int userId) async {
    return await execute(() async {
      await Future.delayed(const Duration(milliseconds: 500));
      return 'User $userId deleted successfully';
    });
  }

  /// 更新用户状态
  Future<bool> updateUserStatus(int userId, bool enabled) async {
    return await executeVoid(() async {
      await Future.delayed(const Duration(milliseconds: 300));
      // 执行更新操作
    });
  }

  @override
  void onSuccess(String data) {
    print('UserAsyncNotifier success: $data');
  }

  @override
  void onVoidSuccess() {
    print('UserAsyncNotifier void success');
  }

  @override
  void onErrorOccurred(dynamic error) {
    print('UserAsyncNotifier error: $error');
  }
}

/// Provider定义
final userListProvider = StateNotifierProvider<UserListNotifier, ListState<ExampleUser>>((ref) {
  final notifier = UserListNotifier();
  // 自动初始化加载
  Future.microtask(() => notifier.initLoad());
  return notifier;
});

final userDetailProvider = StateNotifierProvider.family<UserDetailNotifier, DetailState<ExampleUser>, int>((ref, userId) {
  final notifier = UserDetailNotifier(userId);
  // 自动初始化加载
  Future.microtask(() => notifier.initLoad());
  return notifier;
});

final userFormProvider = StateNotifierProvider<UserFormNotifier, DetailState<ExampleUser>>((ref) {
  return UserFormNotifier();
});

final simpleUserListProvider = StateNotifierProvider<SimpleUserListNotifier, ListState<ExampleUser>>((ref) {
  final notifier = SimpleUserListNotifier();
  // 自动初始化加载
  Future.microtask(() => notifier.initLoad());
  return notifier;
});

final userAsyncProvider = StateNotifierProvider<UserAsyncNotifier, DetailState<String>>((ref) {
  return UserAsyncNotifier();
});

/// 使用示例方法
class ExampleUsage {
  /// 列表使用示例
  static void listExample(WidgetRef ref) {
    // 获取状态
    final listState = ref.watch(userListProvider);
    final listNotifier = ref.read(userListProvider.notifier);

    // 根据状态处理UI
    if (listState.isLoading && listState.data?.isEmpty != false) {
      // 显示加载中
    } else if (listState.hasError && listState.data?.isEmpty != false) {
      // 显示错误页面
    } else if (listState.isEmpty) {
      // 显示空数据
    } else if (listState.isLoaded) {
      // 显示数据列表
      final users = listState.data!;
      // 构建列表UI
    }

    // 操作方法
    // listNotifier.refresh(); // 刷新
    // listNotifier.loadMore(); // 加载更多
    // listNotifier.addItem(user); // 添加数据
    // listNotifier.removeItem(user); // 删除数据
  }

  /// 详情使用示例
  static void detailExample(WidgetRef ref, int userId) {
    // 获取状态
    final detailState = ref.watch(userDetailProvider(userId));
    final detailNotifier = ref.read(userDetailProvider(userId).notifier);

    // 根据状态处理UI
    if (detailState.isLoading && !detailState.hasData) {
      // 显示加载中
    } else if (detailState.hasError && !detailState.hasData) {
      // 显示错误页面
    } else if (detailState.isLoaded) {
      // 显示详情数据
      final user = detailState.data!;
      // 构建详情UI
    }

    // 操作方法
    // detailNotifier.refresh(); // 刷新
    // detailNotifier.updateData(newUser); // 更新数据
  }

  /// 表单使用示例
  static void formExample(WidgetRef ref) {
    final formState = ref.watch(userFormProvider);
    final formNotifier = ref.read(userFormProvider.notifier);

    // 提交表单
    final user = ExampleUser(
      id: 1,
      name: 'New User',
      email: 'new@example.com',
    );

    // formNotifier.submit(user);
  }
}